from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from bs4 import BeautifulSoup
import time


time_begin = time.time()
# 配置 Chrome 选项
options = Options()
options.add_argument("--headless")  # 无界面模式
options.add_argument("--ignore-certificate-errors")  # 忽略 SSL 错误
options.add_argument("--disable-gpu")  # 防止某些情况下的崩溃
options.add_argument("--window-size=1920,1080")  # 让页面按桌面模式加载

# 设置 WebDriver 路径
service = Service("C:/Users/3630/Desktop/py/TCMIP/chromedriver-win64/chromedriver.exe")

# 启动浏览器
driver = webdriver.Chrome(service=service, options=options)

# 访问页面
url = "http://www.tcmip.cn/ETCM2/front/#/browse/traditional_chinese_medicine_formulas"
driver.get(url)

# **等待“简体中文”按钮加载**
try:
    lang_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//a[contains(text(), '简体中文')]"))
    )
    print("找到‘简体中文’按钮，准备点击...")

    # **点击按钮**
    lang_button.click()

    # **等待页面加载完成，等待 id="alltable" 元素可见**
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "alltable")))
    print("‘alltable’元素加载完成，页面准备好了。")

except Exception as e:
    print("遇到错误：", e)

# **获取动态渲染后的 HTML**
page_source = driver.page_source

# **使用 BeautifulSoup 解析页面**
soup = BeautifulSoup(page_source, "lxml")

# **将结果输出到 HTML 文件**
output_file = "output.html"
with open(output_file, "w", encoding="utf-8") as f:
    f.write(soup.prettify())

print(f"抓取的完整页面已保存为 {output_file}")
time_sum = time.time() - time_begin
print(f"总耗时：{time_sum:.2f} 秒")


# 关闭浏览器
driver.quit()
